<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="姓名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button icon="el-icon-search" type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button icon="el-icon-plus" type="primary" v-on:click="handleAdd">新增</el-button>
				</el-form-item>
				<el-form-item>
					<el-popconfirm icon="el-icon-delete" title="确定删除吗？" @confirm="reallyChecked" style="margin-left: 5px;">
						<el-button slot="reference" type="danger">批量删除</el-button>
					</el-popconfirm>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<template>
			<el-table :data="pageInfo.employees" highlight-current-row v-loading="loading" style="width: 100%;"
				@selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55">
				</el-table-column>
				<el-table-column prop="username" label="姓名" width="110" sortable>
				</el-table-column>
				<!-- <el-table-column prop="password" label="密码" width="200" sortable>
				</el-table-column> -->
				<el-table-column prop="email" label="邮箱" width="110" sortable>
				</el-table-column>
				<el-table-column prop="headImage" label="头像" width="150" sortable>
					<!-- <template slot-scope="scope">
						<el-image
      						style="width: 100px; height: 100px"
      						:src=scope.row.headImage></el-image>
					</template> -->
				</el-table-column>
				<el-table-column prop="age" label="年龄" width="110" sortable>
				</el-table-column>
				<el-table-column prop="department.name" label="部门名" width="170" sortable>
				</el-table-column>
				<el-table-column label="操作" width="250">
					<template scope="scope">
						<el-button type="success" size="small" @click="handleEdit(scope.row)">编辑</el-button>
						<el-popconfirm 
							icon="el-icon-delete" 
							title="确定删除吗？" 
							@confirm="handleDel(scope.row.id)"
							style="margin-left: 5px;">
							<el-button slot="reference" size="small" type="danger">删除</el-button>
						</el-popconfirm>
						<el-button type="success" size="small" @click="setRole(scope.row)">角色设置</el-button>
					</template>
				</el-table-column>
			</el-table>
		</template>
		<el-pagination 
			background 
			@size-change="handleSizeChange" 
			@current-change="handleCurrentChange"
			:current-page="this.query.pageNumber" 
			:page-sizes="[5, 10, 20, 40]" 
			:page-size=this.query.pageSize
			layout="total, sizes, prev, pager, next, jumper" 
			:total=this.pageInfo.total>
		</el-pagination>

		<el-dialog 
			title="员工信息" 
			:visible.sync="dialogFormVisible" 
			:close-on-click-modal="false"
			:close-on-press-escape="false" 
			@close="cancel">
			<el-form :model="form">
				<el-form-item label="姓名" :label-width="formLabelWidth">
					<el-input v-model="form.username" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="密码" :label-width="formLabelWidth">
					<el-input v-model="form.password" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" :label-width="formLabelWidth">
					<el-input v-model="form.email" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="头像" :label-width="formLabelWidth">
					<el-input v-model="form.headImage" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="年龄" :label-width="formLabelWidth">
					<el-input v-model="form.age" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="部门名" :label-width="formLabelWidth">
					<el-select v-model="form.department" clearable value-key="id" placeholder="请选择">
						<el-option 
							v-for="item in departments" 
							:key="item.id" 
							:label="item.name" 
							:value="item">
							<span style="float: left">{{item.name }}</span>
							<span style="float: right; color: #8492a6; font-size: 13px">{{item.email }}</span>
						</el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="cancel">取 消</el-button>
				<el-button type="primary" @click="save">确 定</el-button>
			</div>
		</el-dialog>

		<el-dialog 
			title="角色设置" 
			:visible.sync="authFormVisible" 
			:close-on-click-modal="false">
			<el-form :model="roleEmployee" label-width="80px" ref="form" style="margin-left: 5%;">
				<el-checkbox 
					:indeterminate="isIndeterminate" 
					v-model="checkAll"
					style="margin-bottom: 10px ;
					font-weight: bolder"
					@change="handleCheckAllChange">全选</el-checkbox>
				<div class="checkbox-table" v-for="(p, indexkey) in roleTree" :key="p.id">
					<template>
						<el-checkbox 
							class="check" 
							v-model='roleEmployee.roleId' 
							:label="p.id" 
							@change='handleCheck(1, indexkey)'>
							{{ p.name }}
						</el-checkbox>
					</template>
				</div>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="authFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveAuthSubmit">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>
<script>
import { getUserList } from '../../api/api';
//import NProgress from 'nprogress'
export default {
	data() {
		return {
			authFormVisible:false,
			isIndeterminate: false,
			checkAll: false,
			// visible: false,
			loading: false,
			query: {
				pageNumber: 1,
				pageSize: 5,
				keyword: ''
			},
			pageInfo: {
				total: 0,
				employees: []
			},
			selectColumn: [],
			dialogFormVisible: false,
			form: {
				id: null,
				username: '',
				password: '',
				email:'',
				headImage:'',
				age:'',
				department: {
					id: null,
					name: ''
				},
			},
			formLabelWidth: '120px',
			departments:[],
			roleTree:[],
			roleEmployee:{
				roleId:[]
			},
			allEmployeeRoleId:[],
			employeeId:null,
			ImageUrl:''
		}
	},
	methods: {
		queryAllRoleId(){
			this.$http.get('/role/roleId')
				.then(res=>res.data).then(res=>{
					if(res.code == 200){
						this.allEmployeeRoleId = res.data.roleIds
					}
				})
		},
		setRole(row){
			this.employeeId = row.id
			this.authFormVisible = true
			this.getRoleTree();
			this.queryAllRoleId();
			this.queryEmployeeRole();
		
		},
		queryEmployeeRole(){
			this.$http.post("/employee/"+this.employeeId)
        		.then(res=>res.data).then(res=>{
					if(res.code == 200){
						this.roleEmployee.roleId = res.data.empRoles
					}
				})
				.catch(res=>{
					this.$message({type:'danger',message:'网络异常'})
				})
		},
		handleCheck(type){
			let indexOf = this.roleEmployee.roleId.indexOf(this.roleEmployee.roleId);
        	 // 一级菜单点击
        	if (indexOf > -1) { // 已选中的权限中，包含当前一级权限，则将该一级权限下所有的子权限选中
        	  this.roleTree.children.map(item => {
        	    if (this.roleEmployee.roleId.findIndex((n) => n == item.roleId) < 0) {
        	      this.roleEmployee.roleId.push(item.roleId)
        	    }
        	  })
        	}
        	
        	// 获取已选中的长度
        	let checkedCount = this.roleEmployee.roleId.length;
        	// 如果已选中的长度==所有权限的长度，则checkAll=true，也就是全选框被选中
        	this.checkAll = checkedCount === this.allEmployeeRoleId.length;
        	// 如果已选中的长度>0并且已选中的长度<所有权限的长度，则全选框是一个横杠
        	this.isIndeterminate = checkedCount > 0 && checkedCount < this.allEmployeeRoleId.length;
		},
		saveAuthSubmit(){
			let data = {
				id:this.employeeId,
				roleIds:this.roleEmployee.roleId
			}
			//console.log(data);
			this.$http.post("/employee/role",data) // 发送到角色controller 的 permission方法
        		.then(res =>res.data).then(res=>{
					//console.log(res);
					if(res.code == 200){
						this.authFormVisible = false
					}
        		})
				.catch(res =>{
					this.$message({type:'error',message:'网络异常'})
        		})
		},
		handleCheckAllChange(val) {
			this.roleEmployee.roleId = val ? this.allEmployeeRoleId : [];
        	this.isIndeterminate = false;
		},

		getRoleTree(){
			this.$http.get('/role')
				.then(res=>res.data).then(res=>{
					if (res.code == 200) {
						this.roleTree = Object.assign({}, res.data.roles);
					}else{
						this.$message({type:'warning',message:'网络异常'})
					}
				})
				.catch(res=>{
					this.$message({type:'warning',message:'网络异常'})
				})
		},

		//编辑取消方法
		cancel() {
			this.dialogFormVisible = false
			this.getEmployeeList()
		},

		getDepartments(){
			this.$http.get('/department')
				.then(res=>res.data).then(res=>{
					if(res.code == 200){
						this.departments = res.data.departments
					}else{
						this.$message({type:'danger',message:'查询失败'})
					}
				})
				.catch(res=>{
					this.$message({type:'danger',message:'网络异常'})
				})

		},
		
		//编辑按钮触发事件
		handleEdit(row) {
			//console.log(val);
			this.dialogFormVisible = true
			this.getDepartments()
			this.form = Object.assign({}, row);
		},

		//添加信息按钮触发事件
		handleAdd() {
			this.form = {
				id: null,
				username: '',
				password: '',
				email:'',
				headImage:'',
				age:'',
				department: {
					id: null,
					name: ''
				},
			
			}
			this.getDepartments()
			
			this.dialogFormVisible = true
		},
		//保存信息网络请求
		save() {
			let addForm = this.form
			var department = addForm.department
			if(department == ''){
				addForm.department = {
          			id : null,
          			name:""
         		}
			}
			this.$http.post('/employee', addForm)
				.then(res => {
					if (res.data.code == 200) {
						this.dialogFormVisible = false
						this.$message({ message: "操作成功", type: 'success' });
						this.getEmployeeList();
					} else {
						this.$message({ message: res.data.data.msg, type: 'danger' });
					}
				}).catch(res => {
					this.$message({ message: '网络异常', type: 'error' });
				})
		},
		reallyChecked() {
			var ids = this.selectColumn.map(x => x.id);
			if (ids.length == 0) {
				this.$message({ message: '未选中消息', type: 'warning' });
				//return ;
			} else {
				this.batchDelete(ids)
			}
		},
		//批量删除
		batchDelete(ids) {
			//var ids = this.selectColumn.map(x => x.id);
			this.$http.patch("/employee/", ids)
				.then(res => {
					if (res.data.code == 200) {
						this.$message({ message: '删除成功', type: 'success' });
						this.query.pageNumber = 1
						this.getEmployeeList();
					} else {
						this.$message({ message: '请联系管理员!', type: 'warning' });
					}
				}).catch(res => {
					this.$message({ message: '糟糕糟糕偶买噶，魔法怎么失灵了', type: 'warning' });
				})

		},
		
		handleSelectionChange(val) {
			console.log(val);
			this.selectColumn = val
		},
		handleDel(id) {
			console.log(id);
			this.$http.delete("/employee/" + id)
				.then(res => {
					if (res.data.code == 200) {
						this.$message({ message: '删除成功', type: 'success' });
						this.query.pageNumber = 1
						this.getEmployeeList();
					} else {
						this.$message({ message: '请联系管理员!', type: 'danger' });
					}
				}).catch(res => {
					this.$message({ message: '糟糕糟糕偶买噶，魔法怎么失灵了', type: 'warning' });
				})

		},

		search() {
			this.query.pageNumber = 1;
			this.getEmployeeList();
		},
		handleSizeChange(val) {
			this.query.pageSize = val;
			this.query.pageNumber = 1;
			this.getEmployeeList();
		},
		handleCurrentChange(val) {
			this.query.pageNumber = val;
			this.getEmployeeList();
		},
		//获取部门列表
		getEmployeeList: function () {
			this.$http.put('/employee', this.query)
				.then(res => res.data).then(res => {
					if (res.code == 200) {
						this.pageInfo.employees = res.data.employeeList.rows
						this.pageInfo.total = res.data.employeeList.total

					}
				})
				.catch(res => {
					console.log(res);
				})
		}
	},
	mounted() {
		this.getEmployeeList();
	}
};

</script>

<style scoped></style>